package xxl.robotlegs.extensions.viewmanager.impl 
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.utils.Dictionary;
	import xxl.robotlegs.extensions.viewmanager.api.IViewHandler;
	import xxl.signals.api.ISignal;
	import xxl.signals.impl.Signal;
	/**
	 * ...
	 * @author XXL
	 */
	public class ContainerBinding 
	{
		public const bindingEmptySignal:ISignal = new Signal(ContainerBinding);
		private var _parent:ContainerBinding;
		private var _container:DisplayObjectContainer;
		private const _handlers:Vector.<IViewHandler> = new Vector.<IViewHandler>;
		private const _handlerCache:Dictionary = new Dictionary();
		
		public function ContainerBinding(container:DisplayObjectContainer) 
		{
			_container = container;
		}
		
		public function get parent():ContainerBinding 
		{
			return _parent;
		}
		
		public function set parent(value:ContainerBinding):void 
		{
			_parent = value;
		}
		
		public function get container():DisplayObjectContainer 
		{
			return _container;
		}
		
		public function addHandler(handler:IViewHandler):void
		{
			if (_handlerCache[handler])
			{
				return;
			}
			_handlerCache[handler] = true;
			_handlers.push(handler);
		}
		
		public function removeHandler(handler:IViewHandler):void
		{
			delete _handlerCache[handler];
			const index:int = _handlers.indexOf(handler);
			if (index >= 0)
			{
				_handlers.splice(index, 1);
				if (_handlers.length == 0)
				{
					bindingEmptySignal.dispatch(this);
				}
			}
		}
		
		public function handleView(view:DisplayObject, type:Class):void
		{
			const len:int = _handlers.length;
			for (var i:int = 0; i < len; i++) 
			{
				_handlers[i].handleView(view, type);
			}
		}
		
	}

}